<template>
<div>
  <div class="pageTitleWhole">
    <a-breadcrumb>
      <a-breadcrumb-item><router-link to="/landCenter/vehicleInsurance">车辆保险</router-link></a-breadcrumb-item>
      <a-breadcrumb-item>{{menuName}}</a-breadcrumb-item>
    </a-breadcrumb>
  </div>
  <div style="margin: 24px;">
    <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-card>
          <div class="card-title hasContent">保单信息</div>
          <a-row :gutter="[0]">
            <a-col :span="12">
              <a-form-model-item label="车牌号" prop="truckId">
                <a-select
                  show-search
                  v-model="form.truckId"
                  :show-arrow="false"
                  :filter-option="false" :default-active-first-option="false"
                  :not-found-content="null"
                  @search="queryTruckNumberDown"
                  @select="emptyChange0"
                >
                  <a-select-option v-for="d in truckNumberLikeData" :key="d.truckId">{{ d.truckNumber }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="insuranceNo" label="保险单号">
                <a-input v-model="form.insuranceNo" :max-length="30"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="保险种类" prop="insuranceType">
                <a-select v-model="form.insuranceType" class="selectWidth">
                  <a-select-option value="">请选择</a-select-option>
                  <a-select-option value="商业险">商业险</a-select-option>
                  <a-select-option value="交强险">交强险</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="保险公司" prop="custId">
                <a-select
                  show-search
                  v-model="form.custId"
                  :show-arrow="false"
                  :filter-option="false" :default-active-first-option="false"
                  :not-found-content="null"
                  @search="handleNameChange"
                  @select="emptyChange"
                >
                  <a-select-option v-for="d in custInsuranceLikeData" :key="d.id">{{ d.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="insuranceAmount" label="保险金额(元)">
                <a-input-number v-model="form.insuranceAmount" :min="0" :precision="2" :max="999999999999.99" style="width:100%"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="insuranceRebate" label="保险返点">
                <a-input-number v-model="form.insuranceRebate" :min="0" :precision="2"/> %
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="signTime" label="签单日期">
                <a-date-picker :value="form.signTime" @change="onChangeSignTime" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="beginTime" label="生效日期">
                <a-date-picker :value="form.beginTime" @change="onChangeBeginTime" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="handledBy" label="经办人">
                <a-input v-model="form.handledBy" :max-length="10"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="endTime" label="终止日期">
                <a-date-picker :value="form.endTime" @change="onChangeEndTime" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="linkManPhone" label="保险公司联系电话">
                <a-input v-model="form.linkManPhone" :max-length="20"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item prop="linkMan" label="保险公司联系人">
                <a-input v-model="form.linkMan" :max-length="10"/>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card>
          <div class="card-title hasContent">保单合同</div>
          <a-row>
            <a-col :span="12" class="busenPic">
              <a-form-model-item prop="pictures" :wrapperCol="{span:24}" >
                <!-- <ud-upload @uploadFile="picturesUpload" :optList="picturesArr" /> -->
                <a-upload accept=".pdf,.bmp,.jpg,.jpeg,.png,.JPG,.JPEG,.BMP,.PDF,.PNG"
                  :multiple="true"
                  :action="uploadUrl"
                  :headers="headers"
                  :beforeUpload="beforeUpload"
                  :file-list="fileList"
                  @change="handleChange"
                  @preview="previewFile"
                >
                  <a-button> <a-icon type="upload" /> 上传 </a-button>
                </a-upload>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>
    </a-form-model>
  </div>
  <div class="creat_button">
    <a-form-model-item :wrapper-col="{ span: 24 }">
      <a-button type="primary" @click="save" :saveLoading="saveLoading" style="margin-left: 20px; float: right; margin-top:12px;">提交</a-button>
      <a-button @click="cancelCreate" style="float: right; margin-top:12px;">取消</a-button>
    </a-form-model-item>
  </div>
</div>
</template>

<script>
import { VERSION_NO, APP_KEY, REQUEST_INTEFACE_URL } from '@/common/config'
import md5 from 'md5'
import store from 'store'
import Util from '@/common/util'

import debounce from 'lodash/debounce'
// import UpLoad from '@/components/UpLoad'
import {queryCustNameList} from '@/api'
import { queryTruckNumberDown, addTruckContractDetail, queryTruckContractDetail, updateTruckContractDetail } from '@/api/landCenter'

const fomrMessage = `必填项不能为空`

export default {
  data () {
    this.queryTruckNumberDown = debounce(this.queryTruckNumberDown, 800)
    this.handleNameChange = debounce(this.handleNameChange, 800)

    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      truckNumberLikeData: [],
      custInsuranceLikeData: [],
      form: {
        contractId: null,
        truckId: null, //
        insuranceNo: '', // 保险单号
        insuranceType: '', // 保险种类
        insuranceAmount: '', // 保险金额
        insuranceRebate: '', // 保险返点
        signTime: '', // 签单日期
        handledBy: '', // 经办人
        custId: '', // 客户id
        beginTime: '', // 合同生效日期
        endTime: '', // 合同截止时间
        linkMan: '',
        linkManPhone: '',
        pictures: ''
      },
      rules: {
        truckId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        custId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        insuranceNo: [{required: true, message: fomrMessage, trigger: 'blur'}, {message: '只能输入字母和数字', pattern: /^[a-zA-Z0-9]+$/, trigger: 'blur'}],
        insuranceType: [{required: true, message: fomrMessage, trigger: 'blur'}],
        insuranceAmount: [{required: true, message: fomrMessage, trigger: 'blur'}],
        signTime: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        handledBy: [{required: true, message: fomrMessage, trigger: 'blur'}],
        linkMan: [{required: true, message: fomrMessage, trigger: 'blur'}],
        linkManPhone: [{required: true, message: fomrMessage, trigger: 'blur'}],
        beginTime: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        endTime: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        pictures: [{required: true, message: fomrMessage, trigger: 'blur'}]
      },
      saveLoading: false,
      fileList: [],
      headers: {},
      uploadUrl: REQUEST_INTEFACE_URL + '/file/upload'
    }
  },
  // components: {
  //   'ud-upload': UpLoad
  // },
  computed: {
    menuName () {
      return this.$route.query.id ? '编辑保险' : '创建保险'
    }
  },
  created () {
    const contractDetailId = this.$route.query.id
    if (contractDetailId) {
      queryTruckContractDetail({contractDetailId}).then(rsp => {
        Object.assign(this.form, rsp.data)

        const picList = this.form.pictures ? this.form.pictures.split(',') : []
        let optListT = []
        if (picList.length > 0) {
          for (let i = 0; i < picList.length; i++) {
            let pic = picList[i]
            let picName = pic.substr(pic.lastIndexOf('/') + 1)
            let picObj = {
              uid: i,
              name: picName,
              status: 'done',
              url: pic
            }
            optListT.push(picObj)
          }
        }
        this.fileList = optListT
      })
    }
  },
  methods: {
    beforeUpload (file, fileList) {
      if (fileList.length + this.fileList.length >= 100) {
        this.$message.error('最多上传100个文件！')
        return false
      }
      const uuid = Util.getUUID()
      const headers = {
        appKey: APP_KEY,
        version: VERSION_NO,
        timestamp: (() => new Date().getTime())(),
        nonce: uuid,
        token: store.get('token') ? store.get('token') : '',
        sign: md5(`appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase()
      }
      this.headers = headers
    },
    handleChange ({ file, fileList }) {
      let list = [...fileList]
      list = list.map(v => {
        if (v.response) {
          v.url = v.response.data.url
        }
        return v
      })
      this.fileList = list.map((v, i) => {
        if (v.url) {
          let picName = v.url.substr(v.url.lastIndexOf('/') + 1)
          v.name = picName
        }
        return v
      })

      const doneList = list.filter(v => v.url).map(v => v.url)
      this.form.pictures = doneList.length > 0 ? doneList.reduce((pre, current, index, array) => {
        return pre + ',' + current
      }) : ''
    },
    previewFile (file) {
      window.open(file.url, '_blank')
    },
    // picturesUpload (val) {
    //   this.form.pictures = val
    // },
    onChangeSignTime (date, dateString) {
      this.form.signTime = dateString
    },
    onChangeBeginTime (date, dateString) {
      this.form.beginTime = dateString
    },
    onChangeEndTime (date, dateString) {
      this.form.endTime = dateString
    },
    queryTruckNumberDown (truckNumber = '') {
      queryTruckNumberDown({truckNumber, isSelfOperation: 1, status: 1}).then(rsp => {
        this.truckNumberLikeData = rsp.data
      })
    },
    emptyChange0 () {
      this.queryTruckNumberDown()
    },
    handleNameChange (nameLike = '') { // 陆运应付结算对象
      queryCustNameList({
        nameLike,
        belongCompany: 'JIA_TE',
        custTypeLike: 'SUPPLIER',
        status: 1,
        isPayable: 1
      }).then(rsp => {
        this.custInsuranceLikeData = rsp.data
      })
    },
    emptyChange (e) {
      this.handleNameChange()
    },
    cancelCreate () {
      let _t = this
      this.$confirm({
        title: '还有未保存的信息，退出后编辑的数据将消失，确定退出？',
        onOk () {
          _t.$router.push({name: 'landCenter/vehicleInsurance'})
        }
      })
    },
    save () {
      this.saveLoading = true
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          if (this.form.contractId) {
            updateTruckContractDetail(this.form).then(rsp => {
              this.$message.success('提交成功！')
              this.saveLoading = false
              this.$router.push({name: 'landCenter/vehicleInsurance'})
            }).catch(rs => { this.saveLoading = false })
          } else {
            addTruckContractDetail(this.form).then(rsp => {
              this.$message.success('提交成功！')
              this.saveLoading = false
              this.$router.push({name: 'landCenter/vehicleInsurance'})
            }).catch(rs => { this.saveLoading = false })
          }
        }
      })
    }
  },
  mounted () {
    this.queryTruckNumberDown()
    this.handleNameChange()
  }
}
</script>

<style lang="less" scoped>
.ant-card {
  margin-bottom: 24px;
  border: none;
  .card-title {
    position: relative;
    padding-left: 16px;
    font-size: 18px;
    line-height: 1;
    color: #000;
    &:before {
      content: "";
      width: 5px;
      height: 18px;
      background: #1890ff;
      border-radius: 4px;
      position: absolute;
      left: 0;
      top: -1px;
    }
  }
  .hasContent {
    margin-bottom: 20px;
  }
  .ant-col-12{ padding-right: 50px;}
}
#the_module,
.ant-layout{ margin-bottom: 55px;}
.ant-form-item-control{ width: 100%;}
</style>
